<template>
  <div class="register-container">
    <h2 class="login-title">用户注册</h2>
    <van-form @submit="onSubmit" class="form-box">
      <van-cell-group inset>
        <!-- 账号 -->
        <van-field v-model="form.userName" name="账号" label="账号" placeholder="请输入账号"
          :rules="[{ required: true, message: '请填写账号' }]" />

        <!-- 密码 -->
        <van-field v-model="form.password" type="password" name="密码" label="密码" placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]" />

        <!-- 昵称 -->
        <van-field v-model="form.nickName" name="昵称" label="昵称" placeholder="请输入昵称"
          :rules="[{ required: true, message: '请填写昵称' }]" />

        <!-- 签名 -->
        <van-field v-model="form.account" name="签名" label="签名" placeholder="请输入签名"
          :rules="[{ required: true, message: '请填写签名' }]" />
      </van-cell-group>

      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit" :loading="loading" loading-text="注册中...">
          立即注册
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { showSuccessToast, showFailToast } from 'vant';
import axios from 'axios';
import { useRouter } from 'vue-router'; // 新增导入
const router = useRouter(); // 新增路由实例
const form = ref({
  userName: '',
  password: '',
  nickName: '',
  account: '',
  // 固定头像地址
  avatar: 'https://sky-itcast-lkd.oss-cn-beijing.aliyuncs.com/avatar/default.png'
});

const loading = ref(false);

const onSubmit = async () => {
  try {
    loading.value = true;

    const response = await axios.post('http://localhost:8080/register/into', form.value);

    if (response.data.code === '0') {
      showSuccessToast('注册成功');
      setTimeout(() => {
        router.push({ name: 'login' }); // 使用命名路由更安全
      }, 1000);
      // 清空表单
      form.value = {
        userName: '',
        password: '',
        nickName: '',
        account: '',
        avatar: form.value.avatar // 保持固定头像
      };

    } else {
      showFailToast(response.data.msg || '注册失败');
    }
  } catch (error) {
    console.error('注册请求失败:', error);
    showFailToast('注册失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-title {
  text-align: center;
  color: #1989fa;
  margin-top: 2rem;
  font-size: 1.5rem;
}

.register-container {
  padding: 20px;
  min-height: 100vh;
  background: #f7f8fa;
}

.form-box {
  margin-top: 30%;
}

.van-field {
  margin: 8px 0;
  border-radius: 8px;
  background: #fff;
}

.van-button--primary {
  background: #1989fa;
  border: none;
}
</style>